package com.jl.cloud.commom.utils;


import com.jl.cloud.commom.config.RocketMQConfig;
import lombok.extern.slf4j.Slf4j;
import org.apache.rocketmq.client.apis.ClientException;
import org.apache.rocketmq.client.apis.ClientServiceProvider;
import org.apache.rocketmq.client.apis.message.Message;
import org.apache.rocketmq.client.apis.producer.Producer;
import org.springframework.boot.autoconfigure.condition.ConditionalOnBean;

import java.nio.charset.StandardCharsets;

@Slf4j
@ConditionalOnBean(RocketMQConfig.class)
public class RocketMqUtils {


    public static void sendMessage(String topic, String tag,String msg){
        Producer bean = SpringContextHolder.getBean(Producer.class);
        ClientServiceProvider provider = ClientServiceProvider.loadService();
        Message message = provider.newMessageBuilder()
                // Set topic for the current message.
                .setTopic(topic)
                // Message secondary classifier of message besides topic.
                .setTag(tag)
                // Key(s) of the message, another way to mark message besides message id.
                .setKeys("yourMessageKey-1c151062f96e")
                .setBody(msg.getBytes(StandardCharsets.UTF_8))
                .build();
        try {
            bean.send(message);
        } catch (ClientException e) {
            log.error("发送消息失败",e);
            throw new RuntimeException(e);
        }
    }


}
